package com.example.win.android_banduyujia.http.request;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.example.win.android_banduyujia.BanDuApp;
import com.example.win.android_banduyujia.R;
import com.example.win.android_banduyujia.http.HttpResult;
import com.example.win.android_banduyujia.http.HttpUtils;
import com.example.win.android_banduyujia.http.response.BaseHttpResponse;
import com.example.win.android_banduyujia.http.response.ResponseError;
import com.example.win.android_banduyujia.lib.util.Base64Utils;
import com.example.win.android_banduyujia.lib.util.RSAUtils;
import com.example.win.android_banduyujia.peopleactivity.ui.activity.BaseActivity;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.PublicKey;
import java.security.interfaces.RSAKey;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Win on 2015/8/6.
 */
public abstract class BaseHttpRequest {
    public static final String LOG_TAG = AsycHttpRequest.class.getSimpleName();

    public static final String HTTP_METHOD_POST="POST";
    public static final String HTTP_METHOD_GET="GET";

    private static final int ACK_NET_OFF = -6; // 网络异常
    private static final int ACK_CLIENT_EXCEPTION = -5; // 请求过程出现异常
    private static final int ACK_UNKNOW_REQUEST_METHOD = -4; // 非post 也非get 请求
    private static final int ACK_UNKNOW_ERROR = -3; // 网络请求异常
    private static final int ACK_JSON_ERROR = -2; // JSON解析错误
    private static final int ACK_FIALED = -1; // 返回数据中 success= false

    protected static PublicKey mPublicKey;
    private String  mUrl;
    private String  mMethod;
    private Map<String, String>  mParams;
    private Map<String, String>  mHeader;
    private BaseActivity    mContext;

    static {
       /* InputStream inPublic = BanDuApp.getContext().getResources().openRawResource(R.raw.youji_public_key);
        try{
            mPublicKey = RSAUtils.loadPublicKey(inPublic);
        }catch (Exception e){
            e.printStackTrace();
        }*/
    }

    /*public String setHttpParamsToRSA(String info) {
        try{
           String param = new String(Base64Utils.encode(RSAUtils.encryptData(info.getBytes("utf-8"),mPublicKey)));
            return param.substring(0, param.length() - 1);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            return "";
        }
    }*/

    protected  String toHttpMethod(){
        return HTTP_METHOD_GET;
    }

    protected void toHttpRequestParams(Map<String, String> params) { }

    protected void toHttpRequestHeader(Map<String, String> header) { }

    protected abstract String toRequestURL();

    public void setOtherInfoResponse(BaseHttpResponse response) {  }

    public Map<String,String> getHttpParams() {
        Map<String, String> params = new HashMap<String, String>();
        toHttpRequestParams(params);

        for (Map.Entry<String, String>   entry : params.entrySet()) {
            String param = entry.getValue();
            Log.e("param", entry.getKey());
            params.put(entry.getKey(), param);
        }
        return params;
    }

    public Map<String,String> getHttpHeader() {
        Map<String, String>  header = new HashMap<String, String>();
        toHttpRequestHeader(header);
        header.put("User-Agent", "Android");
        return header;
    }

    public void doRequest(BaseActivity context, final Class<? extends BaseHttpResponse> clzz,
                          final Handler callbackHandler,final boolean isShowProgressDialog,final Handler pHandler) {
         if(isShowProgressDialog){
             pHandler.sendEmptyMessage(AsycHttpRequest.CODE_TASK_START);
         }
        mContext = context;
        initRequest();
        Message  msg = new Message();
        HttpResult result = null;
        BaseHttpResponse  response = null;
        ResponseError error = new ResponseError();
        try{
            if(BaseHttpRequest.HTTP_METHOD_POST.equals(mMethod)){
                result = HttpUtils.doPost(mUrl, mHeader, mParams);
            }else if(BaseHttpRequest.HTTP_METHOD_GET.equals(mMethod)){
                result = HttpUtils.doGet(mUrl, mHeader, mParams);
            }else{
                error.setCode(ACK_UNKNOW_REQUEST_METHOD);
                error.setMessage("Unknow request method");
            }
            if(result != null){
                if(result.getErrorCode() == HttpResult.HTTP_RESULT_CODE_SUCCESS
                        && result.getData() != null){
                    Log.v(LOG_TAG, "doRequest: " + result.getData());
                   response = JSON.parseObject(result.getData(), clzz);
                    if(response == null){
                        error.setCode(ACK_JSON_ERROR);
                        error.setMessage("json error");
                    }else{
                        if(!response.isSuccess()){
                            error.setCode(ACK_FIALED);
                            error.setMessage(response.getMessage());
                        }else{
                            setOtherInfoResponse(response);
                            msg.obj = response.saveInfo(response);
                            pHandler.sendEmptyMessage(AsycHttpRequest.CODE_TASK_END);
                            callbackHandler.sendMessage(msg);
                            return;
                        }
                    }
                }else if(result.getErrorCode() == HttpResult.HTTP_RESULT_CODE_NET_OFF){
                    error.setCode(ACK_NET_OFF);
                    error.setMessage("Network unavailable");
                }else{
                    error.setCode(ACK_UNKNOW_ERROR);
                    response.getMessage();
                }
            } else {
                error.setCode(ACK_UNKNOW_ERROR);
                response.getMessage();
            }
             msg.obj = error;
             handler.sendMessage(msg);
             pHandler.sendEmptyMessage(AsycHttpRequest.CODE_TASK_END);
        }catch (Exception  e){
            e.printStackTrace();
        }catch (ExceptionInInitializerError e){
            e.printStackTrace();
             msg.obj = error;
             handler .sendMessage(msg);
             pHandler.sendEmptyMessage(AsycHttpRequest.CODE_TASK_END);
        }
    }

    private final Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            ResponseError  error = (ResponseError) msg.obj;
            mContext.showToast(error.getMessage());
        }
    };

    private void initRequest() {
        mUrl = toRequestURL();
        mMethod = toHttpMethod();
        mParams = getHttpParams();
        mHeader = getHttpHeader();
    }
}
